"""
@name : 2.装饰器
@author : wenyao
@projectname: sanchuanglianxi
"""
#什么是装饰器
#统计一个功能的运行时间

import time
# def func1(a):
#     b = a + 2
#     print(b)
#     time.sleep(1)
#
# def func2(a):
#     b = a + 2
#     print(b)
#     time.sleep(1)

# start = time.time()
# fun1(10)
# end = time.time()
# runtime = end - start
# print(runtime)
#
# start = time.time()
# func2(10)
# end = time.time()
# runtime = end - start
# print(runtime)

# def runtime(func):
#     def inner(args):
#         start = time.time()
#         func(args)
#         end = time.time()
#         runt = end - start
#         print(runt)
#     return inner
#
# inner = runtime(func1)
# inner(10)

# runtime(func1,10)
# runtime(func2,20)

#装饰器
#让我们在不改变函数/类调用方式的情况下给他们添加一些额外的功能
#把函数作为参数，形成的闭包，就是装饰器
# def cost(func):
#     print("i am cost")
#     def _cost(a):
#         start = time.time()
#         print("start......")
#         ret = func(a)
#         print(id(func))
#         end = time.time()
#         print("end.......")
#         runt = end - start
#         print("cost:",runt)
#         return ret
#     return _cost
#
# @cost # -->执行了cost(func1)  #语法糖使用
# def func1(a):
#     b = a + 2
#     print(b)
#     time.sleep(1)
#     return b
# c = func1(10)
# print(id(func1))
#
# @cost
# def func2(a):
#     print(a)
#     time.sleep(2)
#
# c = func1(10)  # --》cost(func1(10))
# c = cost(func1)(10)  #普通调用
# print("xxxxxxxxxx this is c xxxxxxxxxxxxxxxxx")
# print(c)
# func2(20)


#练习
#用装饰器实现简单的权限控制
# username="root"
# def quanxian(func):
#     #global username
#     def inner(a,b):
#         if username=="root":
#             print("欢迎")
#             ret = func(a,b)
#         #print(username)
#             return ret
#         else:
#             print("权限不够")
#     return inner
#
# @quanxian
# def add(a,b):
#     print(f"{a}+{b}={a+b}")
#     return a+b
# b = add(10,20)
# print(b)

#!/bin/python3
#codin=utf-8
import os

def login(func):
    def _test(a,b):
        if os.getuid() == 0:
            A = func(a,b)
            return A
        else:
            print('当前用户无权限执行add函数')
    return _test

@login
def add(num1,num2):
    return num1+ num2

num1 = int(input('请输入num1'))
num2 = int(input('请输入num2'))
a=add(num1,num2)
print(a)